package com.compass.doctor.ui.mine

import android.Manifest
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.TextUtils
import android.text.style.AbsoluteSizeSpan
import android.text.style.ForegroundColorSpan
import android.view.ViewGroup
import androidx.activity.viewModels
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintSet
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import com.compass.doctor.R
import com.compass.doctor.databinding.ActivityEditingNformationBinding
import com.compass.doctor.utils.SelectPicturesUtil
import com.compass.doctor.base.BaseVBActivity
import com.compass.doctor.ui.home.viewmodel.MedicalCareViewModel
import com.compass.doctor.ui.mine.viewmodel.MineViewModel
import com.compass.framework.constant.REFRESH_PATIENT
import com.compass.framework.constant.REFRESH_USER
import com.compass.framework.dialog.ChooseSexDialog
import com.compass.framework.dialog.CommonMessageDialog
import com.compass.framework.ext.onClick
import com.compass.framework.ext.string
import com.compass.framework.ext.toJson
import com.compass.framework.glide.seCircletUrl
import com.compass.framework.glide.setUrlCircle
import com.compass.framework.manager.UserInfoManager
import com.compass.framework.model.ScreenTag
import com.compass.framework.model.User
import com.compass.framework.toast.TipsToast
import com.compass.framework.utils.LiveDataBus
import com.compass.framework.utils.LogUtil
import com.compass.framework.utils.getStringFromResource
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexWrap
import com.google.android.flexbox.FlexboxLayoutManager
import com.google.android.flexbox.JustifyContent
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnPermissionDescriptionListener
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.luck.picture.lib.utils.DensityUtil
import com.luck.picture.lib.widget.MediumBoldTextView
import com.netease.yunxin.kit.corekit.im.IMKitClient
import com.netease.yunxin.kit.corekit.im.model.UserField
import com.netease.yunxin.kit.corekit.im.provider.FetchCallback
import com.netease.yunxin.kit.corekit.im.repo.CommonRepo
import java.io.File

/**
 * Description： 个人资料
 * Date:2023/12/20 9:01
 */

class EditingInformationActivity : BaseVBActivity<ActivityEditingNformationBinding>() {


    companion object {
        fun start(context: Context) {
            val intent = Intent(context, EditingInformationActivity::class.java)
            context.startActivity(intent)
        }
    }

    private val medicalCareViewModel: MedicalCareViewModel by viewModels()
    private val mineViewModel: MineViewModel by viewModels()

    private var avatarPath: String? = null //头像本地path地址
    private var avatar: String? = null //头像
    private var meritIllness: String? = null //擅长疾病
    private var meritTherapeutic: String? = null //擅长治疗
    private var introduce: String? = null //简介
    private var alternativeMobile: String? = null //备用手机号

    override fun initView(savedInstanceState: Bundle?) {

    }


    override fun initData() {
        val user = UserInfoManager.getUserInfo()
        user?.let {
            mBinding.ivHead.setUrlCircle(user.avatar)
            mBinding.etName.text = user.name
            mBinding.tvSex.text = user.getSexString()
            mBinding.tvPhone.text = user.mobile
            mBinding.tvHospitalName.text = user.hospitalName
            mBinding.tvPositionName.text = user.positionName
            mBinding.tvDepartmentName.text = user.departmentName
            mBinding.edtMeritIllness.setText(user.meritIllness)
            mBinding.edtMeritTherapeutic.setText(user.meritTherapeutic)
            mBinding.edtIntroduce.setText(user.introduce)
            mBinding.tvStandbyPhone.setText(user.alternativeMobile)
            meritIllness = user.meritIllness
            meritTherapeutic = user.meritTherapeutic
            introduce = user.introduce
        }

        mineViewModel.updateInfoLiveData.observe(this) {
            dismissLoading()
            it?.let {
                updateUserInfo(it)
                LiveDataBus.get().with(REFRESH_USER).postValue(REFRESH_USER)
                showToast("修改成功")
                finish()
            }
        }
        medicalCareViewModel.updateLiveData.observe(this) {
            it?.let { userAvatar ->
                avatar = userAvatar
                mineViewModel.updateUserInfo(
                    avatar,
                    meritIllness,
                    meritTherapeutic,
                    introduce,
                    alternativeMobile
                )
            } ?: kotlin.run {
                dismissLoading()
            }

        }
    }


    /**
     * 更新用户信息到环信
     */
    private fun updateUserInfo(user: User) {
        var map: MutableMap<UserField, Any> = HashMap(1)

        user.avatar?.let {
            map[UserField.Avatar] = it
        }
        map[UserField.Name] = user.name
        CommonRepo.updateUserInfo(map, object : FetchCallback<Void> {
            override fun onSuccess(param: Void?) {
                LogUtil.e("修改成==onSuccess${param?.toJson()}")
            }

            override fun onException(exception: Throwable?) {
                LogUtil.e("修改成==onException${exception?.toJson()}")
            }

            override fun onFailed(code: Int) {
                LogUtil.e("修改成==onFailed${code}")
            }
        })
    }

    override fun intListener() {
        mBinding.clHead.onClick {
            isGranted()
        }


        mBinding.tvConfirm.onClick {

            meritIllness = mBinding.edtMeritIllness.text.toString().trim()
            meritTherapeutic = mBinding.edtMeritTherapeutic.text.toString().trim()
            introduce = mBinding.edtIntroduce.text.toString().trim()
            alternativeMobile = mBinding.tvStandbyPhone.text.toString().trim()

            if (avatarPath.isNullOrEmpty() && meritIllness.isNullOrEmpty() && meritTherapeutic.isNullOrEmpty() && introduce.isNullOrEmpty() && alternativeMobile.isNullOrEmpty()) {
                showToast("您没有任何信息需要修改")
                return@onClick
            }


            alternativeMobile?.let {
//                if (it.length < 8) {
//                    showToast("请输入正确的备用号码")
//                    return@onClick
//                }
            }



            showLoading()
            if (!avatarPath.isNullOrEmpty()) {
                medicalCareViewModel.upload(File(avatarPath))
            } else {
                mineViewModel.updateUserInfo(
                    avatar,
                    meritIllness,
                    meritTherapeutic,
                    introduce,
                    alternativeMobile
                )
            }

        }


    }

    /**
     * 判断是否有权限
     */
    private fun isGranted() {
        //判断是否有权限
        if (XXPermissions.isGranted(
                this,
                Permission.READ_EXTERNAL_STORAGE,
                Permission.WRITE_EXTERNAL_STORAGE,
                Permission.CAMERA
            )
        ) {
            showChoosePhotoDialog()
        } else {
            CommonMessageDialog.Builder(this)
                .setTitle(getStringFromResource(R.string.permission_explain))
                .setMessage(getStringFromResource(R.string.image_permission_logs))
                .setConfirm(getStringFromResource(com.compass.framework.R.string.default_confirm))
                .setCancel(getString(com.compass.framework.R.string.default_cancel))
                .setonCancelListener {
                    it?.dismiss()
                }
                .setonConfirmListener {
                    showChoosePhotoDialog()
                    it?.dismiss()
                }.create().show()
        }
    }

    /**
     * 选择图片弹框
     */
    private fun showChoosePhotoDialog() {

        XXPermissions.with(this)
            //小米应用市场不允许提前获取相册拍照权限，这里先获取存储权限，进入到相册选择页面点击拍照按钮时在获取拍照权限
            .permission(Permission.READ_EXTERNAL_STORAGE)
            .permission(Permission.WRITE_EXTERNAL_STORAGE)
            .unchecked()
            .request(object : OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                    if (!allGranted) {
                        TipsToast.showTips(R.string.default_agree_permission)
                        return
                    }

                    SelectPicturesUtil.selectPicturesCrop(
                        this@EditingInformationActivity,
                        callbackListener = object : OnResultCallbackListener<LocalMedia> {
                            override fun onResult(result: ArrayList<LocalMedia?>) {
                                avatarPath = result[0]?.availablePath
                                setAvatar(avatarPath)
                            }

                            override fun onCancel() {

                            }
                        })

                }

                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    TipsToast.showTips(R.string.default_agree_permission)
                }
            })
    }



    /**
     * 设置用户头像
     */
    private fun setAvatar(url: String?) {
        mBinding.ivHead.seCircletUrl(url);
    }

}